import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, Image, FlatList, TouchableOpacity } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 推广活动类型定义
interface Promotion {
  id: number;
  title: string;
  description: string;
  image: string;
  startTime: string;
  endTime: string;
  status: 'ongoing' | 'upcoming' | 'ended';
  discount: string;
}

const PromotionPage: React.FC = () => {
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'ongoing' | 'upcoming' | 'ended'>('ongoing');
  const [myQRCode, setMyQRCode] = useState('https://via.placeholder.com/300x300');
  const [shareUrl, setShareUrl] = useState('https://example.com/share/coach123');

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '推广' });
    // 加载推广数据
    loadPromotionData();
  }, []);

  const loadPromotionData = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用
      // const response = await getPromotionsApi();
      
      // 模拟数据
      const mockPromotions: Promotion[] = [
        {
          id: 1,
          title: '春季招生大优惠',
          description: '新学员报名即送价值500元的学车大礼包，包含教材、保险等',
          image: 'https://via.placeholder.com/600x300',
          startTime: '2024-01-01',
          endTime: '2024-03-31',
          status: 'ongoing',
          discount: '立减500元'
        },
        {
          id: 2,
          title: '老学员推荐奖励',
          description: '老学员推荐新学员报名，双方各获得300元现金奖励',
          image: 'https://via.placeholder.com/600x300',
          startTime: '2024-01-01',
          endTime: '2024-12-31',
          status: 'ongoing',
          discount: '300元奖励'
        },
        {
          id: 3,
          title: '暑期特惠班',
          description: '针对学生群体的暑期特惠，C1手动挡学费8折优惠',
          image: 'https://via.placeholder.com/600x300',
          startTime: '2024-06-01',
          endTime: '2024-08-31',
          status: 'upcoming',
          discount: '8折优惠'
        },
        {
          id: 4,
          title: '新年特惠活动',
          description: '元旦期间报名，享受9折优惠并赠送价值200元的礼品卡',
          image: 'https://via.placeholder.com/600x300',
          startTime: '2023-12-25',
          endTime: '2024-01-03',
          status: 'ended',
          discount: '9折优惠'
        }
      ];
      
      setPromotions(mockPromotions);
    } catch (error) {
      console.error('加载推广活动失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSharePromotion = (promotion: Promotion) => {
    // 分享推广活动
    Taro.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    
    Taro.showToast({
      title: '分享功能已开启',
      icon: 'none'
    });
  };

  const handleSaveQRCode = async () => {
    try {
      Taro.showLoading({ title: '保存中...' });
      // 模拟保存二维码到相册
      // 实际应用中应该调用Taro.downloadFile和Taro.saveImageToPhotosAlbum
      setTimeout(() => {
        Taro.hideLoading();
        Taro.showToast({
          title: '二维码已保存到相册',
          icon: 'success'
        });
      }, 1000);
    } catch (error) {
      console.error('保存二维码失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  };

  const handleCopyLink = async () => {
    try {
      await Taro.setClipboardData({
        data: shareUrl
      });
      Taro.showToast({
        title: '链接已复制',
        icon: 'success'
      });
    } catch (error) {
      console.error('复制链接失败:', error);
      Taro.showToast({
        title: '复制失败，请重试',
        icon: 'none'
      });
    }
  };

  const getStatusText = (status: string) => {
    const statusMap: { [key: string]: string } = {
      'ongoing': '进行中',
      'upcoming': '即将开始',
      'ended': '已结束'
    };
    return statusMap[status] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap: { [key: string]: string } = {
      'ongoing': '#52c41a',
      'upcoming': '#faad14',
      'ended': '#8c8c8c'
    };
    return colorMap[status] || '#666';
  };

  const filteredPromotions = promotions.filter(promotion => promotion.status === activeTab);

  return (
    <View className="promotion-page">
      {/* 我的推广二维码区域 */}
      <View className="qrcode-section">
        <View className="qrcode-container">
          <Image 
            className="qrcode-image" 
            src={myQRCode} 
            mode="aspectFit"
          />
          <Text className="qrcode-desc">我的专属推广码</Text>
        </View>
        <View className="qrcode-actions">
          <TouchableOpacity className="action-btn" onPress={handleSaveQRCode}>
            <MaterialIcons name="save-alt" size={28} color="#1890ff" />
            <Text className="action-text">保存二维码</Text>
          </TouchableOpacity>
          <TouchableOpacity className="action-btn" onPress={handleCopyLink}>
            <MaterialIcons name="link" size={28} color="#52c41a" />
            <Text className="action-text">复制链接</Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* 推广活动标签栏 */}
      <View className="tab-bar">
        <TouchableOpacity 
          className={`tab ${activeTab === 'ongoing' ? 'active' : ''}`}
          onPress={() => setActiveTab('ongoing')}
        >
          <Text className="tab-text">进行中</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          className={`tab ${activeTab === 'upcoming' ? 'active' : ''}`}
          onPress={() => setActiveTab('upcoming')}
        >
          <Text className="tab-text">即将开始</Text>
        </TouchableOpacity>
        <TouchableOpacity 
          className={`tab ${activeTab === 'ended' ? 'active' : ''}`}
          onPress={() => setActiveTab('ended')}
        >
          <Text className="tab-text">已结束</Text>
        </TouchableOpacity>
      </View>

      {/* 推广活动列表 */}
      {isLoading ? (
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      ) : (
        <FlatList
          className="promotion-scroll"
          data={filteredPromotions}
          renderItem={({ item }) => (
            <View className="promotion-item">
              <View className="promotion-image-container">
                <Image 
                  className="promotion-image" 
                  src={item.image} 
                  mode="aspectFill"
                />
                <View 
                  className="promotion-status"
                  style={{ backgroundColor: getStatusColor(item.status) }}
                >
                  <Text className="status-text">{getStatusText(item.status)}</Text>
                </View>
              </View>
              <View className="promotion-content">
                <View className="promotion-header">
                  <Text className="promotion-title">{item.title}</Text>
                  <View className="promotion-discount">
                    <Text className="discount-text">{item.discount}</Text>
                  </View>
                </View>
                <Text className="promotion-description">{item.description}</Text>
                <Text className="promotion-period">
                  {item.startTime} - {item.endTime}
                </Text>
                {item.status === 'ongoing' && (
                  <TouchableOpacity 
                    className="share-btn"
                    onPress={() => handleSharePromotion(item)}
                  >
                    <MaterialIcons name="share" size={24} color="#fff" />
                    <Text className="share-btn-text">分享活动</Text>
                  </TouchableOpacity>
                )}
              </View>
            </View>
          )}
          keyExtractor={item => item.id.toString()}
          ListEmptyComponent={() => (
            <View className="empty-container">
              <MaterialIcons name="campaign" size={80} color="#ccc" />
              <Text className="empty-text">暂无推广活动</Text>
            </View>
          )}
        />
      )}
    </View>
  );
};

export default PromotionPage;